package com.lixw.langchain.config;

import com.lixw.langchain.handler.InvoiceHandler;
import com.lixw.langchain.service.FunctionAssistant;
import dev.langchain4j.agent.tool.ToolSpecification;
import dev.langchain4j.agent.tool.ToolSpecifications;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.request.json.JsonObjectSchema;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.tool.ToolExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * @ClassName: LLMConfig
 * @Description:
 * @Author: xuweiLi
 * @Create: 2025/8/24 13:51
 **/
@Slf4j
@Configuration
public class LLMConfig {

    @Bean
    public ChatModel qwenChatModel() {
        return OpenAiChatModel.builder()
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .apiKey(System.getenv("QWEN_API_KEY"))
                .modelName("qwen-plus")
                .build();
    }

    /**
     * 低级API编写FunctionCalling (Tools)
     */
/*    @Bean
    public FunctionAssistant functionAssistant() {
        //创建工具说明对象
        ToolSpecification toolSpecification = ToolSpecification.builder()
                .name("开具发票助手")
                .description("根据用户提交的开票记录，开具发票")
                .parameters(JsonObjectSchema.builder()
                        .addStringProperty("companyName", "公司名称")
                        .addStringProperty("dutyNumber", "税号序列")
                        .addStringProperty("amount", "开票金额，保留两位有效数字")
                        .build())
                .build();

        //工具业务逻辑执行器 ToolExecutor
        ToolExecutor toolExecutor = ((toolExecutionRequest, memoryId) -> {
            log.info("工具执行请求：{}, 记忆id:{}", toolExecutionRequest,memoryId);
            System.out.println(toolExecutionRequest.id());
            System.out.println(toolExecutionRequest.name());
            String arguments = toolExecutionRequest.arguments();
            log.info(">>>>>>>>>args:{}", arguments);
            return "开具成功";
        });

        return AiServices.builder(FunctionAssistant.class)
                .chatModel(qwenChatModel())
                //.tools(toolSpecification, toolExecutor)
                .tools(Map.of(toolSpecification, toolExecutor))
                .build();
    }*/

    @Bean
    public FunctionAssistant functionAssistant() {
        return AiServices.builder(FunctionAssistant.class)
                .chatModel(qwenChatModel())
                .tools(new InvoiceHandler())
                .build();
    }

}